package com.chinaoly.baotou.core.aop;

import com.chinaoly.frm.core.entity.NewRuntimException;
import com.chinaoly.frm.core.entity.ResultCode;
import com.chinaoly.frm.core.entity.ShiroUser;
import com.chinaoly.frm.core.service.BaseService;
import com.chinaoly.baotou.core.UserLocal;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 拦截请求，存放请求用户
 *
 * @author xuyh
 * @date 2022/3/25
 */
@Component
@Aspect
public class UserAop {

    @Autowired
    private BaseService baseService;

    /**
     * 基于注解的切入点
     */
    @Pointcut("@annotation(com.chinaoly.baotou.core.annotation.RequestUser)")
    public void userAspect() {
    }

    @Around(value = "userAspect()")
    public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable {
        ShiroUser user = baseService.getUser();
        if (user.getId() == null) {
            throw new NewRuntimException(ResultCode.E_10013.code, ResultCode.E_10013.getErrorMsg());
        }
        UserLocal.set(user, baseService.getToken());
        Object object = null;
        try {
            object = joinPoint.proceed();
        } finally {
            UserLocal.clean();
        }
        return object;
    }
}
